package edu.udo.sopra10.chaturaji.gui.util;

import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.regex.Pattern;

import javax.swing.JTextField;

/**
 * FocusListener for JTextFields that checks a given regular expression and
 * highlights the text field if the validation fails. 
 *
 * @author Patrick Westerhoff
 */
public class RegExpValidatorFocusListener implements FocusListener
{
	private Pattern regExp;
	
	/**
	 * Constructs the listener.
	 * 
	 * @param regularExpression the pattern to check.
	 */
	public RegExpValidatorFocusListener ( Pattern regularExpression )
	{
		regExp = regularExpression;
	}
	
	@Override
	public void focusGained ( FocusEvent event )
	{}
	
	@Override
	public void focusLost ( FocusEvent event )
	{
		JTextField source  = (JTextField) event.getSource();
		 
		if ( !regExp.matcher( source.getText() ).matches() )
			source.setBackground( new Color( 0xFF9999 ) );
		else
			source.setBackground( Color.WHITE );
	}
}